package net.kevin.demo.hessian.module;

import java.util.HashSet;
import java.util.Set;

import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class InterfaceDependOnRegistry2 implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor {
	private ApplicationContext act;
	private Set<Module> modules;

	public Set<Module> getModules() {
		return modules;
	}

	public void setModules(Set<Module> modules) {
		this.modules = modules;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.act = applicationContext;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	}

	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		for (Module module : modules) {
			for (String facade : module.getFacades()) {
				BeanDefinitionBuilder genericBeanDefinition = BeanDefinitionBuilder
						.genericBeanDefinition(ProxyFactoryBean.class);
				HashSet<String> proxyInterfaces = new HashSet<String>();
				HashSet<String> interceptorNames = new HashSet<String>();
				proxyInterfaces.add(facade);
				interceptorNames.add("InterfaceServiceInterceptor");
				genericBeanDefinition.addPropertyValue("interceptorNames", interceptorNames);
				genericBeanDefinition.addPropertyValue("proxyInterfaces", proxyInterfaces);
				String name = facade.substring(facade.lastIndexOf(".") + 1) + "Remote";
				name = name.substring(0, 1).toLowerCase() + name.substring(1);
				registry.registerBeanDefinition(name, genericBeanDefinition.getBeanDefinition());
			}
		}
	}
}
